<template>
  <div style="width: 80%">
    <div style="margin-bottom: 30px">新增管理员</div>
    <el-form :inline="true" :model="form" :rules="rules" ref="ruleForm" label-width="100px">
      <!-- pro与rules中的属性对应 -->
      <el-form-item label="账号" prop="account">
        <el-input v-model="form.account" placeholder="请输入管理员账号"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" placeholder="请输入管理员密码"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入管理员邮箱"></el-input>
      </el-form-item>
    </el-form>

    <div style="text-align: center; margin-top: 30px">
      <el-button type="primary" @click="save" size="medium">提交</el-button>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: 'AddAdmin',
  data() {
    const checkPassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('密码不能为空'));
      }
      setTimeout(() => {
        if (!/^(?=.*[a-zA-Z])(?=.*\d).{5,25}$/.test(value)) {
          callback(new Error('请至少包括数字和字母且长度大于5'));
            }else {
              callback();
            }
      }, 300);
    };
    return {
      form: {},
      rules: {
        account: [
          {required: true, message: '请输入管理员账号', trigger: 'blur'},
          {min: 1, max: 25, message: '长度在1-25位', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          { validator: checkPassword, trigger: 'blur' }
        ],
      }
    }
  },
  methods: {
    save() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          request.post('/admin/', this.form).then(res => {
            if (res.code === '200') {
              this.$notify.success('新增成功');
              this.$refs['ruleForm'].resetFields();
            } else {
              this.$notify.error(res.msg);
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
  }

}

</script>

